"""
This is the method that will get registered to do the cleanup at the completion
of the script.  It is registered by the atexit() function call
"""

from _spice_path import spice_path

def _finish(spice,scriptglobals,pid):
    #In here we will pop the script from the stack
    oldpidarray=scriptglobals.GetControlValue('pids')
    alreadyexist=pid in oldpidarray
    #Only reset global variables if the PID exists.
    #If it doesn't exist, this SHOULD mean that there are multiple instances
    #of the SPICE class in the script and the globals only need to be reset once.
    if alreadyexist==1:
        oldscriptpaths=scriptglobals.GetControlValue('Script Paths')
        newscriptpaths=oldscriptpaths[0:len(oldscriptpaths)-1]
        newpidarray=oldpidarray[0:len(oldpidarray)-1]
        #Now re-write the new arrays
        if len(oldpidarray)==1:
            bufferglobal=spice.GetVIReference(spice_path + '\\common\\globals\\system_globals.vi')
            bufferglobal.SetControlValue('Script Running',0)
            #print _bufferglobal.GetControlValue('Script Running')
               
        scriptglobals.SetControlValue('Script Paths',newscriptpaths)
        scriptglobals.SetControlValue('pids',newpidarray)
    #print "The finish() method is now finished"
